package com.spk.test.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Wangminze on 2017/3/25.
 * Description:
 */
public class CustomRealm extends AuthorizingRealm {

   /*
   模拟数据库
    */
    private static HashMap<String,String> userInfo = new HashMap<String, String>();

    static{
        userInfo.put("zhangsan","123123");
        userInfo.put("lisi","123456");
        userInfo.put("wangwu","654321");
    }

    //设置一个realmName
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {

        String userCode = (String)authenticationToken.getPrincipal();
        String password = null;

        for (Map.Entry<String,String> entry : userInfo.entrySet() ){

            if ( entry.getKey().equals(userCode) ){

                password = entry.getValue();
                break;
            }
        }
        //返回认证信息，由父类AuthenticationReal进行认证
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(userCode, password, this.getName());
        return simpleAuthenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principalCollection) {
        //自定义一个数据源

        return null;
    }


}
